package com.feng.yupaoback.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import com.feng.yupaoback.common.BaseResult;
import com.feng.yupaoback.common.ErrorCode;
import com.feng.yupaoback.common.ResultUtils;
import com.feng.yupaoback.config.CosClientConfig;
import com.feng.yupaoback.exception.BusinessException;
import com.feng.yupaoback.manager.CosManager;
import com.feng.yupaoback.pojo.dto.UserUpdateInfoRequest;
import com.feng.yupaoback.pojo.entity.User;
import com.feng.yupaoback.service.UserService;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/file")
@Slf4j
@CrossOrigin(origins = {"http://localhost:5173/"}, allowCredentials = "true")
public class FileController {

    @Resource
    private UserService userService;

    @Resource
    private CosManager cosManager;

    @Resource
    private CosClientConfig cosClientConfig;


    /**
     * 测试文件上传
     * @param multipartFile 前端传来的封装文件
     * @return url地址
     */
    @PostMapping("/test/upload")
    public BaseResult<String> testUploadFile(@RequestPart("file") MultipartFile multipartFile) {
        // 文件目录
        String filename = multipartFile.getOriginalFilename();
        String filepath = String.format("/test/%s", filename);
        File file = null;
        try {
            // 上传文件
            file = File.createTempFile(filepath, null);
            multipartFile.transferTo(file);
            cosManager.putObject(filepath, file);
            // 返回可访问地址
            return ResultUtils.success(filepath);
        } catch (Exception e) {
            log.error("file upload error, filepath = " + filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            if (file != null) {
                // 删除临时文件
                boolean delete = file.delete();
                if (!delete) {
                    log.error("file delete error, filepath = {}", filepath);
                }
            }
        }
    }

    /**
     * 测试文件下载
     * @param filepath 文件路径
     * @param response 响应对象
     */
    @GetMapping("/test/download/")
    public void testDownloadFile(String filepath, HttpServletResponse response) throws IOException {
        COSObjectInputStream cosObjectInput = null;
        try {
            COSObject cosObject = cosManager.getObject(filepath);
            cosObjectInput = cosObject.getObjectContent();
            // 处理下载到的流
            byte[] bytes = IOUtils.toByteArray(cosObjectInput);
            // 设置响应头
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + filepath);
            // 写入响应
            response.getOutputStream().write(bytes);
            response.getOutputStream().flush();
        } catch (Exception e) {
            log.error("file download error, filepath = " + filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载失败");
        } finally {
            if (cosObjectInput != null) {
                cosObjectInput.close();
            }
        }
    }

    /**
     * 用户上传头像
     * @param multipartFile 前端传来的封装文件
     * @return url地址
     */
    @PostMapping("/avatar/upload")
    @Transactional(rollbackFor = Exception.class)
    public BaseResult<String> uploadAvatar(@RequestPart("avatar") MultipartFile multipartFile, HttpServletRequest request) {
        this.validPicture(multipartFile);
        // 获取当前用户以及创建信息修改体
        User loginUser = userService.getCurrentUser(request);
        UserUpdateInfoRequest userUpdateInfoRequest = new UserUpdateInfoRequest();

        // 获取头像路径以及进行存储路径的设置
        String path = "User-" + loginUser.getId().toString();
        String uuid =  RandomUtil.randomString(16);
        String suffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());

        String filepath = String.format("/avatar-img/%s/%s.%s", path, uuid, suffix);
        String full_path =  cosClientConfig.getHost() + filepath;
        userUpdateInfoRequest.setAvatarUrl(full_path);
        File file = null;
        try {
            // 上传文件
            file = File.createTempFile(filepath, null);
            multipartFile.transferTo(file);
            cosManager.putObject(filepath, file);
            // 更新数据库
            userService.updateInfo(userUpdateInfoRequest, request);
            // 返回可访问地址
            return ResultUtils.success(filepath);
        } catch (Exception e) {
            log.error("file upload error, filepath = " + filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            this.deleteTempFile(file);
        }
    }

    /**
     * 测试文件下载
     * @param filepath 文件路径
     * @param response 响应对象
     */
    @GetMapping("/avatar/download/")
    public void downloadAvatar(String filepath, HttpServletResponse response) throws IOException {
        COSObjectInputStream cosObjectInput = null;
        try {
            COSObject cosObject = cosManager.getObject(filepath);
            cosObjectInput = cosObject.getObjectContent();
            // 处理下载到的流
            byte[] bytes = IOUtils.toByteArray(cosObjectInput);
            // 设置响应头
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + filepath);
            // 写入响应
            response.getOutputStream().write(bytes);
            response.getOutputStream().flush();
        } catch (Exception e) {
            log.error("file download error, filepath = " + filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载失败");
        } finally {
            if (cosObjectInput != null) {
                cosObjectInput.close();
            }
        }
    }

    /**
     * 验证上传文件
     * @param multipartFile 文件
     */
    public void validPicture(MultipartFile multipartFile) {
        if (multipartFile == null || multipartFile.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件不能为空");
        }
        // 校验文件大小
        long fileSize = multipartFile.getSize();
        final long ONE_MB = 1024 * 1024L;
        if (fileSize > 10*ONE_MB) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件超过上传限制10M");
        }
        // 校验文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        // 允许上传的后缀名
        final List<String> ALLOW_FORMAT_LIST = Arrays.asList("jpeg", "jpg", "png", "webp");
        if (!ALLOW_FORMAT_LIST.contains(fileSuffix)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件类型错误");
        }
    }

    /**
     * 删除临时文件
     * @param file 临时文件
     */
    public void deleteTempFile(File file) {
        if (file == null || !file.exists()) {
           return;
        }
        // 删除临时文件
        boolean result = file.delete();
        if (!result) {
            log.error("file delete error, filepath = {}", file.getAbsolutePath());
        }
    }
}

